// 本地环境
// export const BASE_URL = 'http://192.168.31.125:8080/api/v1'
// 测试环境
// export const BASE_URL = 'https://api.dev.ahgf.org.cn/api/v1'
// 生产环境
export const BASE_URL = 'http://wechat.xiaozhuguang.com/heaven-web/api/v1'
export const MP_BASE_URL = "http://wechat.xiaozhuguang.com"

/**
 * 网络请求request
 * obj.data 请求接口需要传递的数据
 * obj.showLoading 控制是否显示加载Loading 默认为false不显示
 * obj.contentType 默认为 application/json
 * obj.method 请求的方法  默认为GET
 * obj.url 请求的接口路径
 * obj.message 加载数据提示语
 */
let showDisable = false
export function request(obj) {
  return new Promise(function(resolve, reject) {
    showLoading(obj.message? obj.message : '加载中...');
    var data = {};
    if(obj.data) {
      data = obj.data;
    }
    var contentType = 'application/json';
    if(obj.contentType){
      contentType = obj.contentType;
    }

    var method = 'GET';
    if(obj.method){
      method = obj.method;
    }

    uni.request({
      // url: BASE_URL + obj.url,
      url: "/heaven-web/api/v1" + obj.url,
      data: data,
      method: method,
      //添加请求头
      header: {
        'Content-Type': contentType ,
        'agent-token': uni.getStorageSync('agent-token'), //获取保存的token
        "requestId" : randomString(16)
      },
      //请求成功
      success: function(res) {
        console.log('===============================================================================================')
        console.log('==    接口地址：' + obj.url);
        console.log('==    接口参数：' + JSON.stringify(obj.data));
        console.log('==    请求类型：' + method);
        console.log("==    接口状态：" + res.statusCode);
        console.log("==    接口数据：" + JSON.stringify(res.data));
        console.log('===============================================================================================')
        if (res.statusCode >= 400) {
          showToast("请求服务异常，请重试")
          reject("请求异常，请重试")
          return
        }
        let code = res.data.code
        if (code === 200) {
          resolve(res.data.payload)
        } else if (code === 401) {//授权失效
          uni.setStorageSync('token', '')
          startLogin();//跳转到登录页
          reject("登录已过期");
        } else if (code === 403) {
          if (showDisable) {
            return;
          }
          showDisable = true
          uni.showModal({
            title: '账号异常提醒',
            content: '您的账号存在异常，请联系管理员！',
            showCancel: false,
            confirmText: '我知道了',
            confirmColor: '#8bc124',
            complete: () => {
              showDisable = false
            }
          })
        } else {
          //请求失败
          showToast(res.data.msg)
          reject("请求失败：" + res.data.msg)
        }
      },
      fail: function(err) {
        //服务器连接异常
        console.log('===============================================================================================')
        console.log('==    接口地址：' + obj.url)
        console.log('==    接口参数：' + JSON.stringify(obj.data))
        console.log('==    请求类型：' + obj.method)
        console.log("==    服务器连接异常")
        console.log('===============================================================================================')
        showToast('服务器连接异常，请检查网络再试')
        reject("服务器连接异常，请检查网络再试");
      },
      complete: function() {
        hideLoading()
      }
    })
  });
}

export function startLogin() {
  let pages = getCurrentPages()
  let page = pages[pages.length - 1]
  console.log(page)
  window.location.href = BASE_URL +"/wxMp/auth?authType=agent&referer=" + MP_BASE_URL +"/agent/";
}

export const showToast = function(content, duration) {
  if(!duration) duration = 2000
  uni.showToast({
    title: content,
    icon: 'none',
    duration: duration,
  })
}

var isShowLoading = false
export const showLoading = function(title) {
  if(isShowLoading) return
  uni.showLoading({
    title: title ? title:'',
    duration: 2000,
    mask:true,
    success:()=>{
      isShowLoading = true
    }
  })
}

export const hideLoading = function() {
  isShowLoading = false
  uni.hideLoading()
}

function randomString(length) {
  var str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  var result = '';
  for (var i = length; i > 0; --i)
    result += str[Math.floor(Math.random() * str.length)];
  return result;
}